package com.cn.tutorialjava.demos.web.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;

public class GzipUtils {
    public static byte[] compressString(String data) throws IOException {
        if (data == null || data.isEmpty()) {
            return null;
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
        try (GZIPOutputStream gzipOS = new GZIPOutputStream(bos)) {
            gzipOS.write(data.getBytes(StandardCharsets.UTF_8));
        }
        return bos.toByteArray();
    }

    /**
     * 把头部设置成 gzip格式
     * @param uncompressedData
     * @param status
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> createGzipResponseEntity(String uncompressedData, HttpStatus status) throws IOException {
        byte[] compressedData = compressString(uncompressedData);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Encoding", "gzip");
        headers.set("Content-Type", "application/geo+json");
        return new ResponseEntity<>(compressedData, headers, status);
    }
}
